package com.feeling.oafeeling.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.feeling.oafeeling.pojo.SysUser;
import com.feeling.oafeeling.utils.util.ServletUtils;
import com.feeling.oafeeling.utils.util.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author Administrator
 */
@Service("ss")
@Slf4j
public class PermissionService {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private TokenService tokenService;

    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";

    /** 管理员角色权限标识 */
    private static final String SUPER_ADMIN = "admin";

    private static final String ROLE_DELIMETER = ",";

    private static final String PERMISSION_DELIMETER = ",";

    public boolean hasPermi(String permission)
    {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        HttpServletRequest request = ServletUtils.getRequest();
        Long token = tokenService.verifyToken(request.getHeader("Access-Token"));
        SysUser sysUser = new SysUser();
        sysUser.setUserId(token);
        log.info("111111"+sysUser.getUserId());
        Set<String> list = sysPermissionService.getMenuPermission(sysUser);
        sysUser.setPermissions(list);
        if (ObjectUtil.isNull(sysUser) || CollectionUtils.isEmpty(sysUser.getPermissions())) {
            return false;
        }
        return hasPermissions(sysUser.getPermissions(), permission);
    }


    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission)
    {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }


}
